package com.lzy.elasticserch.config;

import com.lzy.util.IndexMappingUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;
import java.util.stream.Collectors;

@Configuration
@EnableConfigurationProperties({IndexMappingProperty.class})
public class IndexMappingConfig {
    @Autowired
    private IndexMappingProperty property;

    @Bean
    public IndexMappingManage getIndexMappingManage() {
        return new IndexMappingManage(property);
    }


    public static class IndexMappingManage {
        private final Map<String, IndexMappingProperty.Mapping> map;

        public IndexMappingManage(IndexMappingProperty property) {
            this.map = init(property);
        }

        /**
         * 获取索引
         *
         * @param schema 数据库 schema
         * @param table  据库表名称
         * @return
         */
        public String getIndex(String schema, String table) {
            IndexMappingProperty.Mapping mapping = map.get(IndexMappingUtil.getMappingKey(schema, table));
            if (mapping == null) {
                throw new RuntimeException("未知的索引配置");
            }
            return mapping.getIndexAlias();
        }

        /**
         * 获取索引
         *
         * @param schema   数据库 schema
         * @param table    据库表名称
         * @param tenantId 多租户表,租户id
         * @return
         */
        public String getIndex(String schema, String table, Long tenantId) {
            String sourceTable = table.replaceAll("_" + tenantId, "");
            return getIndex(schema, sourceTable);
        }


        private Map<String, IndexMappingProperty.Mapping> init(IndexMappingProperty property) {
            return property.getMappings().stream()
                    .collect(Collectors.toMap(o -> IndexMappingUtil.getMappingKey(o.getSchemaName(), o.getTableName()), o -> o));
        }
    }
}
